package com.ishanggang.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BaiduLatAndLngUtil {
    private static final Logger logger = LoggerFactory.getLogger(BaiduLatAndLngUtil.class);
    public static final String AK = "MrtLHcEtSkXQd8FoV0Gxu2PVsNdWgDag";
    public static final String LNG = "lng";
    public static final String LAT = "lat";

    public static Map<String, String> addressToLngAndLag(String address) {
        try {
            String res;
            String oldAddress = address;
            address = URLEncoder.encode(address, "UTF-8");
            URL resjson = new URL("http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=" + AK);
            BufferedReader in = new BufferedReader(new InputStreamReader(resjson.openStream()));
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            in.close();
            String str = sb.toString();
            HashMap<String, String> map = null;
            if (str != null) {
                int lngStart = str.indexOf("lng\":");
                int lngEnd = str.indexOf(",\"lat");
                int latEnd = str.indexOf("},\"precise");
                if (lngStart > 0 && lngEnd > 0 && latEnd > 0) {
                    String lng = str.substring(lngStart + 5, lngEnd);
                    String lat = str.substring(lngEnd + 7, latEnd);
                    map = new HashMap<String, String>();
                    map.put(LNG, lng);
                    map.put(LAT, lat);
                    return map;
                }
                logger.info("地址:{}无法转经纬度-原因{}", (Object) oldAddress, (Object) str);
            }
        } catch (Exception e) {
            logger.error("BaiduLatAndLngUtil.getLatitude", e);
        }
        return null;
    }
}
